package gold.digger;

import gold.utils.InputUtil;
import gold.vo.TreeNode;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1339 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        Map<TreeNode, Long> memo = new HashMap<>();
        public static final int factor = 1000000000 + 7;
        long totalSum = 0, ans = 0;

        public int maxProduct(TreeNode root) {
            totalSum = dfsGetNodeSum(root);
            dfsGetMaxProduct(root);
            return (int) (ans % factor);
        }

        public void dfsGetMaxProduct(TreeNode root) {
            if (null == root) return;
            // remove root left side link
            if (null != root.left) {
                long removeLeft = memo.get(root.left) * (totalSum - memo.get(root.left));
                ans = Math.max(ans, removeLeft);
                dfsGetMaxProduct(root.left);
            }

            // remove root right side link
            if (null != root.right) {
                long removeRight = memo.get(root.right) * (totalSum - memo.get(root.right));
                ans = Math.max(ans, removeRight);
                dfsGetMaxProduct(root.right);
            }
        }

        public long dfsGetNodeSum(TreeNode root) {
            if (null == root) return 0;
            long nodeSum = root.val + dfsGetNodeSum(root.left) + dfsGetNodeSum(root.right);
            memo.put(root, nodeSum);
            return nodeSum;
        }
    }

    public void run() {
        System.out.println(new Solution().maxProduct(TreeNode.createTree("[1,null,2,3,4,null,null,5,6]")));
        System.out.println(new Solution().maxProduct(TreeNode.createTree("[2,3,9,10,7,8,6,5,4,11,1]")));
        System.out.println(new Solution().maxProduct(TreeNode.createTree("[1,1]")));
    }

    public static void main(String[] args) throws Exception {
        LC1339 an = new LC1339();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
